﻿using System;
using System.Globalization;
using System.Net.Http;
using Newtonsoft.Json;

namespace GoogleGeocode
{

    public class GoogleGeocodeRequest
    {
        // get address by coords
        public GoogleGeocodeRequest(float latitude, float lontitude, GoogleLanguage lang = GoogleLanguage.en)
        {
            this._latitude = latitude.ToString(CultureInfo.InvariantCulture);
            this._longitude = lontitude.ToString(CultureInfo.InvariantCulture);
            this._language = lang;
        }
        // get coords by address
        public GoogleGeocodeRequest(string address, GoogleLanguage lang = GoogleLanguage.en)
        {
            this._address = address;
            throw new NotImplementedException();
        }

        private readonly string _latitude;
        private readonly string _longitude;
        private readonly string _address;
        private readonly GoogleLanguage _language;
        private const string ApiUrl = "http://maps.googleapis.com/maps/api/geocode/json?sensor=false&latlng={0},{1}&language={2}";

        public GoogleGeocodeResponse Get()
        {
            var geocode = new RawResponse();
            var url = String.Format(ApiUrl, _latitude, _longitude, _language.ToString());
            var client = new HttpClient();
            var response = client.GetAsync(url);
            if (response.Result.IsSuccessStatusCode)
            {
                var result = response.Result.Content.ReadAsStringAsync().Result;
                geocode = JsonConvert.DeserializeObject<RawResponse>(result);
            }
            return new GoogleGeocodeResponse(geocode);
        }

    }
}
